/*
 * Copyright (C) 2012 DataSymphony (http://datasymphony.com.au)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package au.com.ds.restty;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import au.com.ds.restty.Out.Level;
import au.com.ds.restty.cmd.Command;
import au.com.ds.restty.cmd.impl.ArgumentListImpl;
import au.com.ds.restty.cmd.impl.TemplateManager;
import au.com.ds.restty.exc.InvalidInput;
import au.com.ds.restty.fmt.Formatter;
import au.com.ds.restty.fmt.FormatterFactory;
import au.com.ds.restty.http.HttpConnector;


public class Client {
	private static final Logger LOG = LoggerFactory.getLogger(Client.class); 
	private static final String PARAM_PROFILE = "restty.profile";
	private static final String PARAM_DEF_PROFILE = "restty";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		boolean contextInitialized = false;
		try {
			int minParams = 1;
			// process output level parameter
			if (args.length > 0 && args[0] != null && args[0].startsWith("-o=")) {
				String[] pair = args[0].split("=");
				if (pair.length != 2) {
					throw new InvalidInput("Invalid \"o\" parameter: " + args[0]);
				}
				
				Level level = null;
				try {
					level = Level.valueOf(pair[1]);					
				} catch (IllegalArgumentException e){
					throw new InvalidInput("Invalid \"o\" parameter value: " + pair[1]);					
				}
				
				Out.setLevel(level);
				minParams++;			
			} else {
				Out.setLevel(Level.normal);
			}
			
			Out.normal("Copyright (C) 2012 DataSymphony (http://datasymphony.com.au)");
			Out.normal("Restty 0.22 (May 6th 2012)");
			Out.normal("");
			
			if (args.length < minParams){
				throw new InvalidInput("Usage: restty [-o=min|normal|debug] command_name [arg1] [arg2] [arg3_name=arg3_value] ...");
			}
			
			String profileName = System.getProperty(PARAM_PROFILE);
			if (profileName == null){
				profileName = PARAM_DEF_PROFILE;
			}
			
			new ExecutionContext(profileName, new ArgumentListImpl(args, minParams));
			contextInitialized = true;
					
			TemplateManager templates = new TemplateManager();
			
			Command cmd = templates.buildCommand();
			
			HttpConnector http = new HttpConnector();
			cmd.exec(http);
			
			Formatter fmt = FormatterFactory.getFormatter(cmd);		
			String result = fmt.getFormattedResult();
			
			Out.normal("Response Body:");
			Out.min(result);			
		} catch (Exception e){
			if (contextInitialized) {
				LOG.error("Error during command execution", e);
			}
			
			Out.finalError(e.getMessage());
		}
	}
}
